package com.school.dao.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.school.dao.AdminDao;
import com.school.domain.Admin;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl implements AdminDao {
    private QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
    @Override
    public Admin findById(long aid) {
        List<Admin> execute;
        try {
            execute = queryRunner.query("select * from administrator where aid = " + aid, new BeanListHandler<>(Admin.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
        if (execute.size() < 1) return null;
        return execute.get(0);
    }

    @Override
    public boolean update(Admin admin) {
        int result;
        try {
            result = queryRunner.update("update administrator set name = ?, pwd = ? where aid = ?", admin.getName(), admin.getPwd(), admin.getAid());
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }
}
